package liecai_class.day09;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * NIO客户端
 */
public class Demo08 {
    public static void main(String[] args) throws IOException {
        //1.创建sc
        SocketChannel sc = SocketChannel.open();
        //2.开启sc的非阻塞模式
        sc.configureBlocking(false);
        //3.向连接服务器发起了连接
        sc.connect(new InetSocketAddress("127.0.0.1",9999));
        //4.完成和服务器的连接
        while(!sc.finishConnect()){
        }
        //5.向服务器发送数据
        ByteBuffer buf = ByteBuffer.wrap("hello nio!".getBytes());
        while(buf.hasRemaining()){
            sc.write(buf);
        }
        //6.接受服务器返回的数据
        ByteBuffer buf2 = ByteBuffer.allocate(11);
        while(buf2.hasRemaining()){
            sc.read(buf2);
        }
        String msg = new String(buf2.array());
        System.out.println("服务器返回的数据:"+msg);
        //6.关闭通道
        sc.close();
    }
}
